package com.oron3.lock;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


public class AES {
	private   byte[] m_key ; 
	private final  SecretKeySpec m_sskey;
	private  Cipher m_AEScipher;

	public AES(final String key) throws UnsupportedEncodingException, NoSuchAlgorithmException 
	{
		byte[] keyBytes = key.getBytes("UTF-8");
		final MessageDigest sha = MessageDigest.getInstance("SHA-1");
		keyBytes = sha.digest(keyBytes);
		final byte[] byte16 = new byte[16];
		final Random rand = new Random();
		for (int i = 0 ; i < 16 ; i++) {
			byte16[i] =  keyBytes[i];
		}
		m_sskey = new SecretKeySpec(byte16, "AES");
	}


	public byte[] decrypt(final byte[] p_msg) throws Exception{      
		final Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, m_sskey);
		final byte[] dec = cipher.doFinal(p_msg);
		return dec;
	}
	public byte[] encrypt(final byte[] p_msg) throws Exception{
		final Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, m_sskey);
		final byte[] dec = cipher.doFinal(p_msg);
		return dec;
	}

	public ByteArrayInputStream decrypt(final InputStream inputStream) throws IllegalBlockSizeException, BadPaddingException, IOException {
		final byte[] dec = m_AEScipher.doFinal(IOUtils.getBytes(inputStream));
		return new ByteArrayInputStream(dec);
	}


	String decodeUTF8(final byte[] bytes) throws UnsupportedEncodingException {
		return new String(bytes, "UTF-8");
	}

	byte[] encodeUTF8(final String string) throws UnsupportedEncodingException {
		return string.getBytes("UTF-8");
	}

	public String encrypt(final String str) throws Exception {
		final byte[] encrypt = encrypt(encodeUTF8(str));
		final byte[] encoded = Base64.encodeBase64(encrypt);
		return new String(encoded);
	}
	public String decrypt(final String str) throws Exception {
		final byte[] decoded = Base64.decodeBase64(str.getBytes());  
		final byte[] dec = decrypt(decoded);
		return  decodeUTF8(dec);
	}


}